package com.hjl.sessions; /**
 * @author ServivE
 * @className ${NAME}
 * @description ${description}
 * @version 0.1
 * @date 2024/7/27 15:20
 * @since jdk11
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SessionServlet", value = "/ss")
public class SessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 1.session是自动创建的（服务器）
     * 2.session是借助cookie将id发送给客户端
     * 3.服务器会为每一次会话创建一个session
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //通过request对象获取session对象
        HttpSession session = request.getSession();
        //使用session保存数据
        session.setAttribute("username","zhang3");
        //使用request保存数据
        request.setAttribute("username","zhang4");
        //重定向到getValue（重定向是两次请求，但属于同一个会话）而request只一次请求有效
        response.sendRedirect("/getValue");
        System.out.println(session.getId());
    }
}
